//
//  UIView+Extension.swift
//  AIPhotoProcess
//
//  Created by aw031 on 17/10/2025.
//

import Foundation
import UIKit

extension UIView {
    // MARK: - Frame 属性
    /// 获取或设置视图的左边界（x）
    var left: CGFloat {
        get { return frame.minX }
        set { frame.origin.x = newValue }
    }
    /// 获取或设置视图的上边界（y）
    var top: CGFloat {
        get { return frame.minY }
        set { frame.origin.y = newValue }
    }
    /// 获取或设置视图的右边界（x+width）
    var right: CGFloat {
        get { return frame.maxX }
        set { frame.origin.x = newValue - frame.size.width }
    }
    /// 获取或设置视图的下边界（y+height）
    var bottom: CGFloat {
        get { return frame.maxY }
        set { frame.origin.y = newValue - frame.size.height }
    }
    /// 获取或设置视图的宽度
    var width: CGFloat {
        get { return frame.size.width }
        set { frame.size.width = newValue }
    }
    /// 获取或设置视图的高度
    var height: CGFloat {
        get { return frame.size.height }
        set { frame.size.height = newValue }
    }
    /// 获取或设置视图中心点的x坐标
    var centerX: CGFloat {
        get { return center.x }
        set { center.x = newValue }
    }
    /// 获取或设置视图中心点的y坐标
    var centerY: CGFloat {
        get { return center.y }
        set { center.y = newValue }
    }
    /// 获取或设置视图的尺寸（宽高）
    var size: CGSize {
        get { return frame.size }
        set { frame.size = newValue }
    }
    
    /// 给视图添加点击事件
    /// - Parameters:
    ///   - target: 目标对象
    ///   - action: 响应方法
    func addTarget(_ target: Any, action: Selector) {
        isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: target, action: action)
        addGestureRecognizer(tap)
    }

    // MARK: - 视图层级
    /// 获取当前视图所在的顶层控制器（向上遍历superview）
    func topViewController() -> UIViewController? {
        var next: UIView? = self.superview
        while let view = next {
            if let responder = view.next, let vc = responder as? UIViewController {
                return vc
            }
            next = view.superview
        }
        return nil
    }
    /// 移除所有子视图
    func removeAllSubviews() {
        subviews.forEach { $0.removeFromSuperview() }
    }

    // MARK: - 圆角、阴影
    /// 设置部分圆角和边框
    /// - Parameters:
    ///   - cornerRadius: 圆角半径
    ///   - borderWidth: 边框宽度
    ///   - borderColor: 边框颜色
    ///   - corners: 需要设置圆角的角
    func setBorder(cornerRadius: CGFloat, borderWidth: CGFloat, borderColor: UIColor, corners: UIRectCorner) {
        setBorder(cornerRadius: cornerRadius, viewSize: size, borderWidth: borderWidth, borderColor: borderColor, corners: corners)
    }
    /// 设置部分圆角和边框（可指定视图尺寸）
    /// - Parameters:
    ///   - cornerRadius: 圆角半径
    ///   - viewSize: 视图尺寸
    ///   - borderWidth: 边框宽度
    ///   - borderColor: 边框颜色
    ///   - corners: 需要设置圆角的角
    func setBorder(cornerRadius: CGFloat, viewSize: CGSize, borderWidth: CGFloat, borderColor: UIColor, corners: UIRectCorner) {
        // 绘制圆角路径
        let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: viewSize.width, height: viewSize.height),
                                byRoundingCorners: corners,
                                cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
        
        // 创建CAShapeLayer来绘制圆角边框
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.strokeColor = borderColor.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineWidth = borderWidth
        shapeLayer.lineJoin = .round
        shapeLayer.lineCap = .round
        layer.addSublayer(shapeLayer)
        
        // mask遮罩，保证圆角效果
        let maskPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: viewSize.width, height: viewSize.height),
                                    byRoundingCorners: corners,
                                    cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
        
        // 创建遮罩CAShapeLayer
        let maskLayer = CAShapeLayer()
        maskLayer.path = maskPath.cgPath
        layer.mask = maskLayer
    }
    
    /// 设置黑色透明度0.08的阴影
    func setViewWithShadowColorBlackAlpha008() {
        setViewWithShadowColor(UIColor.black.withAlphaComponent(0.08))
    }
    /// 设置黑色透明度0.1的阴影
    func setViewWithShadowColorBlackAlpha03() {
        setViewWithShadowColor(UIColor.black.withAlphaComponent(0.3))
    }
    
    /// 设置黑色透明度0.1的阴影
    func setViewWithShadowColorBlackAlpha01() {
        setViewWithShadowColor(UIColor.black.withAlphaComponent(0.1))
    }
    
    
    /// 设置自定义颜色的阴影
    /// - Parameter shadowColor: 阴影颜色
    func setViewWithShadowColor(_ shadowColor: UIColor , shadowOffset : CGSize = .zero , shadowRadius : CGFloat = 5) {
        layer.shadowColor = shadowColor.cgColor
        layer.shadowOffset = shadowOffset
        layer.shadowOpacity = 1
        layer.shadowRadius = shadowRadius
    }
    
    /// 截取整个视图的内容
        func takeScreenshot() -> UIImage? {
            UIGraphicsBeginImageContextWithOptions(bounds.size, false, 2.0)
            defer { UIGraphicsEndImageContext() }
            
            drawHierarchy(in: bounds, afterScreenUpdates: true)
            return UIGraphicsGetImageFromCurrentImageContext()
        }
        
        /// 使用现代API（iOS 10+）
        func takeScreenshotModern() -> UIImage? {
            let renderer = UIGraphicsImageRenderer(bounds: bounds)
            return renderer.image { context in
                layer.render(in: context.cgContext)
            }
        }

    

    // MARK: - xib
    /// 从xib创建视图
    class func getCreatNibView<T: UIView>(bundle: Bundle? = nil) -> T? {
        let nibName = String(describing: self)  // 获取调用者的类名
        let bundle = Bundle(for: self)          // 使用 self 而不是 T.self
        let nib = UINib(nibName: nibName, bundle: bundle)
        guard let view = nib.instantiate(withOwner: nil, options: nil).first as? T else {
            fatalError("Could not load view from nib with name \(nibName)")
        }
        return view
    }
    /// 创建一个极小的header/footer视图（常用于UITableView占位）
    static func creatHeaderAndFooterView() -> UIView {
        return UIView(frame: CGRect(x: 0, y: 0, width: 0.01, height: 0.01))
    }
    
    /// 创建一个极小的header/footer视图（常用于UITableView占位）
    func createDashedBorderLayer( color: UIColor,viewSize : CGSize = .zero, cornerRadius: CGFloat,
        lineWidth: CGFloat = 1, dashPattern: [NSNumber] = [8, 2]
    ) {
        let borderLayer = CALayer.createDashedBorderLayer(color: color, viewSize: viewSize, cornerRadius: cornerRadius, lineWidth: lineWidth, dashPattern: dashPattern)
        layer.addSublayer(borderLayer)
    }
    
    func addHeartbeatAnimation(shakeCount: Int) {
        let animation = CAKeyframeAnimation(keyPath: "transform.scale")
        
        // 使用更清晰的配置
        animation.values = [1.0, 1.1,  1.0]
        animation.keyTimes = [0.0 ,0.5, 1.0].map { NSNumber(value: $0) }
        animation.duration = 1.0
        animation.repeatCount = Float(shakeCount)
        
        animation.timingFunctions = [
            CAMediaTimingFunction(name: .linear),
            CAMediaTimingFunction(name: .linear),
            CAMediaTimingFunction(name: .linear)
        ]
        
        
        self.layer.add(animation, forKey: "heartbeat")
    }

    private func configureHeartbeatAnimation(_ animation: CAKeyframeAnimation, shakeCount: Int) {
        animation.values = [1.0, 1.1, 1.0, 1.2, 1.0, 1.0]
        animation.keyTimes = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0].map { NSNumber(value: $0) }
        animation.duration = 1.0
        animation.repeatCount = Float(shakeCount)
        
        animation.timingFunctions = [
            CAMediaTimingFunction(name: .easeIn),
            CAMediaTimingFunction(name: .easeOut),
            CAMediaTimingFunction(name: .linear),
            CAMediaTimingFunction(name: .easeIn),
            CAMediaTimingFunction(name: .easeOut),
            CAMediaTimingFunction(name: .easeIn)
        ]
    }
    
}
